package main

import "fmt"

func updateSlice(s []int) { //切片参数，[]无固定长度，引用传递
	s[0] = 100
}

func main() {
	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7} //可变长度，数组

	fmt.Println("arr[2:6] =", arr[2:6]) //左闭右开 [2,3,4,5]
	fmt.Println("arr[:6] =", arr[:6])   //从0开始，到索引6之前（左闭右开） [0,1,2,3,4,5]
	s1 := arr[2:]                       //从2到结束 [2,3,4,5,6,7]
	fmt.Println("s1 =", s1)
	s2 := arr[:] //全部 [0,1,2,3,4,5,6,7]
	fmt.Println("s2 =", s2)

	fmt.Println("After updateSlice(s1)")
	updateSlice(s1)
	fmt.Println(s1)
	fmt.Println(arr)

	fmt.Println("After updateSlice(s2)")
	updateSlice(s2)
	fmt.Println(s2)
	fmt.Println(arr)

	fmt.Println("Reslice")
	fmt.Println(s2)
	s2 = s2[:5]
	fmt.Println(s2)
	s2 = s2[2:]
	fmt.Println(s2)

	fmt.Println("Extending slice")
	arr[0], arr[2] = 0, 2
	fmt.Println("arr =", arr)
	s1 = arr[2:6] //[2,3,4,5] [6,7]
	//切片可以继续切片...对同一个array的view，切片具有只能向后扩展
	s2 = s1[3:5] //[5,6]     [s1[3], s1[4]],s1[4]直接取是取不出来的，但是继续切片是可以获取的
	fmt.Printf("s1=%v, len(s1)=%d, cap(s1)=%d\n",
		s1, len(s1), cap(s1)) //%v数组值
	fmt.Printf("s2=%v, len(s2)=%d, cap(s2)=%d\n",
		s2, len(s2), cap(s2))

	s3 := append(s2, 10) //再array索引内，修改数组元素值
	s4 := append(s3, 11) //超出array索引，slice不再是对array的view，而是重新分配新的数组拷贝到新的数组中
	s5 := append(s4, 12)
	fmt.Println("s3, s4, s5 =", s3, s4, s5)
	// s4 and s5 no longer view arr.
	fmt.Println("arr =", arr)

	// Uncomment to run sliceOps demo.
	// If we see undefined: sliceOps
	// please try go run slices.go sliceops.go
	fmt.Println("Uncomment to see sliceOps demo")
	//sliceOps()
}
